package com.baizhi;

import ch.qos.logback.core.encoder.ByteArrayUtil;
import ch.qos.logback.core.util.FileUtil;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

public class RequestDemo {
    public static String carNoDis(byte[] imgData){
        String path = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";

        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);


        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 设置query参数
        request.addQueryParameter("access_token", "24.5e3ff7af587d37aa453030b61431eb35.2592000.1650088661.282335-25779700");



        //将图片字节数组转为Base64编码的字符串换
        String imgStr = Base64.encodeBase64String(imgData);

        //将经过Base64编码的图片字符串转为UTF-8编码的字符串。可以直接传给image参数

        try {
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String jsonBody = "image="+imgParam;
            request.setJsonBody(jsonBody);

            ApiExplorerClient client = new ApiExplorerClient();
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            System.out.println(response.getResult());
            String result = response.getResult().substring(27,34);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void testImg() throws IOException {
        String filePath = "d:/test.png";
        //将图片转为字节数组
        byte[] imgData = FileUtils.readFileToByteArray(new File(filePath));
        String s = carNoDis(imgData);
        System.out.println(s);
    }

}
